package com.cqupt.controller;


import com.cqupt.common.log.annotation.OperationLog;
import com.cqupt.mapper.BusinessMapper;
import com.cqupt.pojo.ResponseMessage;
import com.cqupt.service.HostService;
import com.cqupt.service.ReportExportService;
import com.cqupt.utils.DateUtils;
import com.sun.org.apache.xpath.internal.objects.XObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.rmi.MarshalledObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@Controller
@RequestMapping("report")
@ResponseBody
public class ReportExportController {

    @Autowired
    private ReportExportService reportExportService;

    @Autowired
    private HostService hostService;


    /**
     * 报表测试
     * status   可用/不可用
     * hostType 服务器/网络设备
     *             0    1
     * @param params
     * @return
     */
    @RequestMapping("/export_data")
    public void Export_Data(@RequestBody Map<String, Object> params){
        String status = params.get("status").toString();
        Integer hostType = Integer.valueOf(params.get("hostType").toString());
        reportExportService.ExportData(status,hostType);
    }

    /**
     * 性能分析报表
     * hostid   主机id
     * status   可用/不可用
     * hostType 服务器/网络设备
     *             0    1
     * @param params
     * @return
     */
    @OperationLog(level = "信息", object = "性能分析报表", operationType = "导出")
    @RequestMapping("/export_performance_excel")
    public ResponseMessage Export_Performance_Excel(@RequestBody Map<String, Object> params, HttpServletResponse response){
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resMap = new HashMap<>();
        String hostid = params.get("hostid").toString();
        String startTime = params.get("startTime").toString();
        String endTime = params.get("endTime").toString();
        String name = hostService.get_name_by_hostid(hostid);   //通过hostid获得设备名称
        Boolean status = reportExportService.getItem_by_DataInfo(hostid,startTime,endTime,response); //通过时间，设备hostid获得监控项信息
        resMap.put("log_objectName",name+"性能分析报表");
        if (status == true){
            resMap.put("log_description","导出"+name+"性能数据");
        }else{
            responseMessage.setErrorCode("已存在"+name+"性能分析报表"+"!");
        }
        responseMessage.setContent(resMap);
        responseMessage.setStatus(status);
        return responseMessage;
    }

    /**
     * 性能报表web端展示性能数据所用接口
     * 参数  hostid 通过hostid获得当前选择框中主机的趋势
     * @return
     */
    @RequestMapping("/performance_info")
    public ResponseMessage Performance_info(@RequestBody Map<String, Object> params){
        String hostid = params.get("hostid").toString();
        String startTime = params.get("startTime").toString();
        String endTime = params.get("endTime").toString();
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String,Object> resultMap = new HashMap<>();
        List<List> resultList = reportExportService.getItemDataInfo_select_event(hostid,startTime,endTime); //通过时间，设备hostid获得监控项数据
        resultMap.put("result",resultList);
        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);
        return responseMessage;
    }


    /**
     * 运行分析报表
     * status   可用/不可用
     * hostType 服务器/网络设备
     *             0    1
     * @param params
     * @return
     */
    @OperationLog(level = "信息", object = "巡检报告", operationType = "导出")
    @RequestMapping("/export_inspection_excel")
    public ResponseMessage Export_Inspection_Excel(@RequestBody Map<String, Object> params, HttpServletResponse response){
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resMap = new HashMap<>();
        String statu = params.get("status").toString();
        Integer hostType = Integer.valueOf(params.get("hostType").toString());
        Boolean status = reportExportService.InspectionData(statu,hostType,response); //根据hostType分类
        if (0==hostType){
            resMap.put("log_objectName","服务器巡检报告");
            if (status == true){
                resMap.put("log_description","导出服务器巡检报告");
            }else{
                responseMessage.setErrorCode("已存在设备资源统计报表!");
            }
            responseMessage.setContent(resMap);
            responseMessage.setStatus(status);
        }else {
            resMap.put("log_objectName","网络设备巡检报告");
            if (status == true){
                resMap.put("log_description","");
            }else{
                responseMessage.setErrorCode("导出网络设备巡检报告!");
            }
            responseMessage.setContent(resMap);
            responseMessage.setStatus(status);
        }
        return responseMessage;
    }

    /**
     * 告警统计报表
     * 格式为   yyyy-MM-dd HH-mm-ss  默认为空（即  "" ）
     * startDate    开始时间
     * endDate      结束时间
     * @param params
     * @return
     */
    @OperationLog(level = "信息", object = "告警信息报表", operationType = "导出")
    @RequestMapping("/export_alert_excel")
    public ResponseMessage Export_Alert_Excel(@RequestBody Map<String, Object> params,HttpServletResponse response){
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resMap = new HashMap<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  //格式化时间
        String startDate = "";
        try{
            startDate = params.get("startDate").toString();
            startDate = df.format(new Date(Long.parseLong(String.valueOf(startDate))));
        }catch (Exception e){
            e.getMessage();
        }
        String endDate = "";
        try{
            endDate = params.get("endDate").toString();
            endDate = df.format(new Date(Long.parseLong(String.valueOf(endDate))));
        }catch (Exception e){
            e.getMessage();
        }
        if ("".equals(startDate) && "".equals(endDate)){    //没有时间默认前一周即604800ms
            endDate = df.format(new Date());
            //  默认一周，即从当前位置开始后退604,800秒
            //  一周     604 800
            //  一月  18 144 000
            //  一年 217 728 000
            startDate = DateUtils.SecondTimeStamp2Date((DateUtils.timeToStamp(endDate)/1000-604800l)+"");
        }
        System.out.println(startDate+"  ,   "+endDate);

        Boolean status = reportExportService.getHistoryAlert(startDate,endDate, response);
        resMap.put("log_objectName","告警信息报表");
        if (status == true){
            resMap.put("log_description","");
        }else{
            responseMessage.setErrorCode("已存在告警信息报表!");
        }
        responseMessage.setContent(resMap);
        responseMessage.setStatus(status);
        return responseMessage;
    }

    /**
     * 告警统计报表
     * 格式为   yyyy-MM-dd HH-mm-ss  默认为空（即  "" ）
     * startDate    开始时间
     * endDate      结束时间
     * @param params
     * @return 历史告警，未处理告警，和两个总和
     */
    @RequestMapping("/getChartsData")
    public ResponseMessage getChartsData(@RequestBody Map<String, Object> params){
        ResponseMessage responseMessage = new ResponseMessage();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//格式化时间
        String startDate = params.get("startDate").toString();
        String endDate = params.get("endDate").toString();
        if ("".equals(startDate) && "".equals(endDate)){//没有时间默认前一周即604800ms
            endDate = df.format(new Date());
            //  默认一周，即从当前位置开始后退604,800秒
            //  一周     604 800
            //  一月  18 144 000
            //  一年 217 728 000
            startDate = DateUtils.SecondTimeStamp2Date((DateUtils.timeToStamp(endDate)/1000-604800l)+"");
        }else {
            startDate = df.format(new Date(Long.parseLong(String.valueOf(startDate))));
            endDate = df.format(new Date(Long.parseLong(String.valueOf(endDate))));
        }
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        List<List> chartData = reportExportService.getAlarmDistributionAndChartData(startDate, endDate);
        Map<String, Object> resultMap = new HashMap<String, Object>(){{
            put("result", chartData);
        }};
        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);
        return responseMessage;
    }

    /**
     * 告警信息报表 web展示top10
     * 格式为   yyyy-MM-dd HH-mm-ss  默认为空（即  "" ）
     * startDate    开始时间
     * endDate      结束时间
     * @param params
     * @return
     */
    @RequestMapping("/show_alert_top10")
    public ResponseMessage Show_alert_top10(@RequestBody Map<String, Object> params){
        ResponseMessage responseMessage = new ResponseMessage();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//格式化时间
        String startDate = "";
        try{
            startDate = params.get("startDate").toString();
            startDate = df.format(new Date(Long.parseLong(String.valueOf(startDate))));
        }catch (Exception e){
            e.getMessage();
        }
        String endDate = "";
        try{
            endDate = params.get("endDate").toString();
            endDate = df.format(new Date(Long.parseLong(String.valueOf(endDate))));
        }catch (Exception e){
            e.getMessage();
        }
        if ("".equals(startDate) && "".equals(endDate)){//没有时间默认前一周即604800ms
            endDate = df.format(new Date());
            //  默认一周，即从当前位置开始后退604,800秒
            //  一周     604 800
            //  一月  18 144 000
            //  一年 217 728 000
            startDate = DateUtils.SecondTimeStamp2Date((DateUtils.timeToStamp(endDate)/1000-604800l)+"");
        }
        startDate = startDate+" 00:00:00";
        endDate = endDate + " 23:59:59";
        String dataStr = DateUtils.timeToStamp(startDate)+","+DateUtils.timeToStamp(endDate);
        System.out.println(dataStr);

        List<Map<String,Object>> resultList = reportExportService.getAlertTop10(dataStr);
        Map<String,Object> result = new HashMap<>();
        result.put("result",resultList);
        responseMessage.setContent(result);
        responseMessage.setStatus(true);
        return responseMessage;
    }


    /**
     * 告警信息报表
     * 格式为   yyyy-MM-dd HH-mm-ss  默认为空（即  "" ）
     * startDate    开始时间
     * endDate      结束时间
     * @param params
     * @return
     */
    @OperationLog(level = "信息", object = "告警统计报表", operationType = "导出")
    @RequestMapping("/export_alert_statistics_excel")
    public ResponseMessage Export_Alert_Statistics_Excel(@RequestBody Map<String, Object> params,HttpServletResponse response){
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resMap = new HashMap<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间
        String startDate = "";
        try{
            startDate = params.get("startDate").toString();
            startDate = df.format(new Date(Long.parseLong(String.valueOf(startDate))));
        }catch (Exception e){
            e.getMessage();
        }
        String endDate = "";
        try{
            endDate = params.get("endDate").toString();
            endDate = df.format(new Date(Long.parseLong(String.valueOf(endDate))));
        }catch (Exception e){
            e.getMessage();
        }
        String imgsURl = params.get("imgsURl").toString();
//        System.out.println(imgsURl);
        if ("".equals(startDate) && "".equals(endDate)){
            endDate = df.format(new Date());
            //  默认一周，即从当前位置开始后退604,800秒
            //  一周     604 800
            //  一月  18 144 000
            //  一年 217 728 000
            startDate = DateUtils.SecondTimeStamp2Date((DateUtils.timeToStamp(endDate)/1000-604800l)+"");
        }
        Boolean status = reportExportService.getHistoryAlertClassify(startDate,endDate,imgsURl,response);
        resMap.put("log_objectName","告警统计报表");
        if (status == true){
            resMap.put("log_description","");
        }else{
            responseMessage.setErrorCode("已存在告警统计报表!");
        }
        responseMessage.setContent(resMap);
        responseMessage.setStatus(status);
        return responseMessage;
    }


    /**
     * 资源统计报表
     * 无参 ，导出全部报表信息
     * @return
     */
    @RequestMapping("/export_statistics_excel")
    public void Export_Statistics_Excel(HttpServletResponse response){
        reportExportService.getResource(response);
    }

    /**
     * 新 资源统计报表
     * @return
     */
    @OperationLog(level = "信息", object = "资源统计报表", operationType = "导出")
    @RequestMapping("/export_statistics_excel_new")
    public ResponseMessage Export_Statistics_Excel_New(@RequestBody Map<String,Object> params,HttpServletResponse response){
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resMap = new HashMap<>();
        String hostType = params.get("hostType").toString();
        Boolean status = reportExportService.getResource_new(hostType,response);
        if ("0".equals(hostType)){
            resMap.put("log_objectName","设备资源统计报表");
            if (status == true){
                resMap.put("log_description","");
            }else{
                responseMessage.setErrorCode("已存在设备资源统计报表!");
            }
            responseMessage.setContent(resMap);
            responseMessage.setStatus(status);
        }else {
            resMap.put("log_objectName","业务资源统计报表");
            if (status == true){
                resMap.put("log_description","");
            }else{
                responseMessage.setErrorCode("已存在设备资源统计报表!");
            }
            responseMessage.setContent(resMap);
            responseMessage.setStatus(status);
        }
        return responseMessage;
    }
    /**
     * 资源统计报表web展示接口
     * @return
     */
    @RequestMapping("/statistics_charts")
    public ResponseMessage Statistics_Excel_Charts(final String hostType){
        ResponseMessage responseMessage = new ResponseMessage();
        List<Map<String,Object>> result = reportExportService.getRsource_charts(hostType);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("result",result);
        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);
        return responseMessage;
    }

    /**
     * 获得所有可用设备
     * @return
     */
    @RequestMapping("/get_all_online_host")
    public ResponseMessage getAllOnlineHost() {
        ResponseMessage responseMessage = new ResponseMessage();
        final List<Map<String, Object>> resultList = reportExportService.getAllOnlineHost();
        Map<String, Object> resultMap = new HashMap<String, Object>(){{
            put("result", resultList);
        }};
        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);
        return responseMessage;
    }

    /**
     * 通过设备hostid获得一个主机的信息
     * @param params
     * @return
     */
    @RequestMapping("/get_a_host")
    public ResponseMessage getAOnlineHost(@RequestBody Map<String, Object> params) {
        ResponseMessage responseMessage = new ResponseMessage();
        String hostid = params.get("hostid").toString();
        final List<Map<String, Object>> resultList = reportExportService.getAllOnlineHost(hostid);
        Map<String, Object> resultMap = new HashMap<String, Object>(){{
            put("result", resultList);
        }};
        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);
        return responseMessage;
    }

}
